package com.vrv.common.resolver.dispatcher;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.vrv.common.resolver.RequestParameter;
import com.vrv.common.resolver.Response;
import com.vrv.common.resolver.locality.DBManager;

/**
 * content://com.vrv.sqlite/dbname
 *
 * @author 曹保利
 *
 */
public class LocalityRequestHandler implements RequestState {

    @Override
    public Response handler(Context mContext, RequestParameter parameter, String[] detailKeys) {

        String uri = parameter.getUrl();
        String tableName = uri.substring(uri.lastIndexOf("/") + 1);
        String pageCount = "SELECT COUNT(*) from " + tableName + " WHERE 1=1 " + getFilterSql(parameter);
        String pageSql = "SELECT * from " + tableName + " WHERE 1=1 " + getFilterSql(parameter) + " LIMIT " + parameter.getPageSize() + " OFFSET "
                + (parameter.getPageSize() * (parameter.getPageNumber() + 1));

        Response response = new Response();
        try {
            ArrayList<Map<String, Object>> records = new ArrayList<Map<String, Object>>();
            int totalRecords = DBManager.getInstance(mContext).getCount(pageCount);
            DBManager.getInstance(mContext).open();
            SQLiteDatabase sqliteDb = DBManager.getInstance(mContext).getMSQLiteDatabase();
            Cursor mCursor = sqliteDb.rawQuery(pageSql, null);
            while (mCursor.moveToNext()) {
                Map<String, Object> varMap = new HashMap<String, Object>();
                for (int i = 0; i < detailKeys.length; i++) {
                    int columnIndex = mCursor.getColumnIndex(detailKeys[i]);
                    varMap.put(detailKeys[i], mCursor.getString(columnIndex));
                }
                records.add(varMap);
            }
            DBManager.getInstance(mContext).close();
            response.setTotalRecords(totalRecords);
            response.setRecords(records);
            response.setSuccess(Boolean.TRUE);
            return response;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return response;
    }

    private String getFilterSql(RequestParameter parameter) {
        return "";
    }
}
